#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import os
import sys
import codecs
import sqlite3
 
# set default encoding as UTF-8
reload(sys)
#sys.setdefaultencoding('utf-8')
# connect_database
# if db exists,connect it
# else create db file
def connect_db(db_name):
    conn = sqlite3.connect(db_name)
    return conn
 
# close connect
def close_db(conn):
    if conn is not None:
        conn.close()
 
# insert values into table
def insert_values(conn, table_name):
  
    cu = conn.cursor()
    try:
        cu.execute("insert into %s values (\'%s\',\'%d\')" % (table_name, 'xxx', 12))
    except sqlite3.Error, e:
        print 'insert value failed:', e.args[0]
        return
    conn.commit()
 
 
# query values from table
def query_values(conn, table_name):
    cu = conn.cursor()
 
    try:
        cu.execute('select * from %s' % table_name)
    except sqlite3.Error, e:
        print 'query data failed:', e.args[0]
        return
    return cu.fetchall()
 
 
# create table
def create_table(conn, table_name):
    cu = conn.cursor()
    try:
        cu.execute('create table %s (Name,Age integer) ' % table_name)
    except sqlite3.Error, e:
        print 'create table failed:', e.args[0]
        return
    conn.commit()
 
# drop table if exist
def drop_table(conn, table_name):
    cu = conn.cursor()
  
    try:
        cu.execute('drop table if exists %s' % table_name)
    except sqlite3.Error, e:
        print 'drop table failed:', e.args[0]
        return
    conn.commit()
 
# main function
if __name__ == '__main__':
    db_name = './Per.db'
    conn = connect_db(db_name)
    table_name = 'per'
    drop_table(conn, table_name)
    create_table(conn, table_name)
 
  
    close_db(conn)
